package com.rongshu.view.home.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Constant;
import com.rongshu.utils.GlideUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.AdapterListener;
import com.rongshu.view.discovery.bean.ArticleDetaisRequest;
import com.rongshu.view.home.activity.SingleArticleDetailsActivity;
import com.rongshu.view.home.bean.RecommendReaderResponse;
import com.rongshu.view.submitArticle.bean.LabelBean;
import com.rongshu.widget.ArticleLabelView;
import com.utils.FastClickUtils;
import com.widget.CircleImageView;
import com.widget.SwipeMenuView;
import com.widget.toast.ToastUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * created by zhengweis on 2019/2/12.
 * description：他人的文章列表item（包括当前用户：分享、转载、收藏的文章）
 */
public class RecommendArticleAdapter extends RecyclerView.Adapter<RecommendArticleAdapter.ViewHolder> {

    protected Context context;
    protected List<RecommendReaderResponse.ResponseBean> list;
    private AdapterListener listener;

    public RecommendArticleAdapter(Context context, List<RecommendReaderResponse.ResponseBean> list) {
        this.list = list;
        this.context = context;
    }

    public void setAdapterListener(AdapterListener listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.adapter_article_othres, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int position) {
        if (list.get(position).getIsIsRead() != 0) {
            viewHolder.articleTitle.setTextColor(ContextCompat.getColor(context, R.color.color_898989));
        } else {
            viewHolder.articleTitle.setTextColor(ContextCompat.getColor(context, R.color.color_2c2c2c));
        }
        //文章标题
        viewHolder.articleTitle.setText(list.get(position).getTitle());
        //文章简介
        viewHolder.articleContent.setText(list.get(position).getContents_header());
        //作者
        viewHolder.articleAuthor.setText(list.get(position).getBi_name());
        //文字栏目
        viewHolder.articleCategory.setText(list.get(position).getCategories());
        //文章标签
        StringBuilder builder = new StringBuilder();
        List<LabelBean> keywordList = list.get(position).getKeywordList();
        for (int index = 0; index < keywordList.size(); index++) {
            builder.append(index < keywordList.size() - 1 ?
                    keywordList.get(index).getTitle() + " | " : keywordList.get(index).getTitle());
        }
        viewHolder.articleLabels.setText(builder);
        //文字头图
        viewHolder.articleImg.setVisibility(TextUtils.isEmpty(list.get(position).getTopImg()) ? View.GONE : View.VISIBLE);
        GlideUtils.loadImageView(context, viewHolder.articleImg, list.get(position).getTopImg(),
                R.drawable.default_preview_icon, R.drawable.default_preview_icon);
        //文章推荐人数 + 推荐者头像
        bindRecommendView(viewHolder, list.get(position));
        //侧滑
        viewHolder.removeItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    if (list.get(position).getIsIsRead() != 0) {
                        listener.callBack(list.get(position));
                        list.remove(position);
                        notifyItemRemoved(position);
                        notifyItemRangeChanged(position, list.size() - position);//通知数据与界面重新绑定
                    } else {
                        ToastUtils.show("未读文章，无法移除");
                        viewHolder.swipemenuView.smoothClose();
                    }
                }
            }
        });
        //进入单个文章详情
        viewHolder.contentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!FastClickUtils.isFastClick()) {
                    list.get(position).setIsRead(0);
                    Intent intent = new Intent(context, SingleArticleDetailsActivity.class);
                    intent.putExtra(Constant.ARTICLE_DETAILS_REQUEST, convertBean(list.get(position)));
                    context.startActivity(intent);
                    list.get(position).setIsRead(1);
                    notifyDataSetChanged();
                }
            }
        });
    }


    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.article_img)
        ImageView articleImg;
        @BindView(R.id.article_title)
        TextView articleTitle;
        @BindView(R.id.article_content)
        TextView articleContent;
        @BindView(R.id.remove_item)
        TextView removeItem;
        @BindView(R.id.swipemenu_view)
        SwipeMenuView swipemenuView;
        @BindView(R.id.article_category)
        TextView articleCategory;
        @BindView(R.id.article_author)
        TextView articleAuthor;
        @BindView(R.id.article_labels)
        TextView articleLabels;
        @BindView(R.id.head_1)
        CircleImageView head1;
        @BindView(R.id.head_2)
        CircleImageView head2;
        @BindView(R.id.head_3)
        CircleImageView head3;
        @BindView(R.id.artile_recommend_count)
        TextView artileRecommendCount;
        @BindView(R.id.content_layout)
        LinearLayout contentLayout;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    //文章推荐人数 + 头像
    private void bindRecommendView(ViewHolder viewHolder, RecommendReaderResponse.ResponseBean responseBean) {
        List<RecommendReaderResponse.ResponseBean.RecommendAvatarBean> recommendAvatar = responseBean.getRecommendAvatar();
        if (UserInfoUtils.getUserInfo() != null) {
            String hint = responseBean.getRecommendCount() <= 3 ? "" : "等";
            viewHolder.artileRecommendCount.setText(hint + responseBean.getRecommendCount() + "人推荐");
        } else {
            viewHolder.artileRecommendCount.setText("读者推荐");
        }
        for (int index = 0; index < recommendAvatar.size(); index++) {
            switch (index) {
                case 0:
                    viewHolder.head1.setVisibility(View.VISIBLE);
                    viewHolder.head2.setVisibility(View.GONE);
                    viewHolder.head3.setVisibility(View.GONE);
                    viewHolder.head1.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_stroke_white_background_5dp));
                    GlideUtils.loadImageView(context, viewHolder.head1, recommendAvatar.get(index).getAvatar(),
                            R.drawable.user_head_icon, R.drawable.user_head_icon);
                    break;
                case 1:
                    viewHolder.head1.setVisibility(View.VISIBLE);
                    viewHolder.head2.setVisibility(View.VISIBLE);
                    viewHolder.head3.setVisibility(View.GONE);
                    viewHolder.head2.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_stroke_white_background_5dp));
                    GlideUtils.loadImageView(context, viewHolder.head2, recommendAvatar.get(index).getAvatar(),
                            R.drawable.user_head_icon, R.drawable.user_head_icon);
                    break;
                case 2:
                    viewHolder.head1.setVisibility(View.VISIBLE);
                    viewHolder.head2.setVisibility(View.VISIBLE);
                    viewHolder.head3.setVisibility(View.VISIBLE);
                    viewHolder.head3.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_stroke_white_background_5dp));
                    GlideUtils.loadImageView(context, viewHolder.head3, recommendAvatar.get(index).getAvatar(),
                            R.drawable.user_head_icon, R.drawable.user_head_icon);
                    break;
            }
        }
    }

    private ArticleDetaisRequest convertBean(RecommendReaderResponse.ResponseBean response) {
        ArticleDetaisRequest bean = new ArticleDetaisRequest();
        bean.setContribute_id(response.getContribute_id());
        bean.setType(Constant.FROM_RECOMMEND);
        bean.setTopic_id(0);
        return bean;
    }

    //      Item缩放的动画
//      这个Item动画不仅仅可以缩小高度，也可以左右滑动删除等
    private void collapse(final View view, Animation.AnimationListener al) {
        final int originHeight = view.getMeasuredHeight();
        Animation animation = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                if (interpolatedTime == 1.0f) {
                    view.getLayoutParams().height = originHeight;//更改部分避免删除两个Item
                } else {
                    view.getLayoutParams().height = originHeight - (int) (originHeight * interpolatedTime);
                }
                view.requestLayout();
            }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };
        if (al != null) {
            animation.setAnimationListener(al);
        }
        animation.setDuration(200);
        view.startAnimation(animation);
    }

    /**
     * 删除Item动画
     *
     * @param viewHolder
     * @param position
     */
    private void deleteItem(final ViewHolder viewHolder, final int position) {

        Animation.AnimationListener al = new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                list.remove(position);
                viewHolder.swipemenuView.quickClose();
                notifyDataSetChanged();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        };
        collapse(viewHolder.itemView, al);
    }
}